// src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import store from '../store'; // 确保正确引入 Vuex store
import Login from '@/views/Login.vue';
import Home from '@/views/Home.vue';
import PublicActivities from '@/views/PublicActivities.vue';
import ActivityDetail from '@/views/ActivityDetail.vue';
import ActivityManagement from '@/views/ActivityManagement.vue';

Vue.use(Router);

const routes = [
  { path: '/login', component: Login },
  { path: '/', component: Home },
  { path: '/public-activities', component: PublicActivities },
  { path: '/public-activities/:id', component: ActivityDetail },
  { path: '/activity-management', component: ActivityManagement }
];

const router = new Router({
  mode: 'history',
  routes
});

router.beforeEach((to, from, next) => {
  const user = store.state.user; // 通过 Vuex store 获取用户状态
  if (!user && (to.path !== '/login')) {
    next('/login');
  } else if (to.path === '/activity-management' && user.role !== 'admin') {
    alert('无权限访问');
    next('/');
  } else {
    next();
  }
});

export default router;